"""

"""

from kivymd.uix.screen import MDScreen
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.button import MDRaisedButton, MDFlatButton
from kivymd.uix.toolbar import MDTopAppBar
from kivymd.app import MDApp
from kivymd.toast import toast
import threading
import time

from ..components.progress_card import ProgressCard
from ..components.video_info_card import VideoInfoCard
from ...core.video_processor import VideoProcessor
from ...core.transcriber import WhisperTranscriber
from ...core.summarizer import VideoSummarizer
from ...core.ollama_client import OllamaClient

class ProcessingScreen(MDScreen):
    """"""
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.processing = False
        self.processing_thread = None
        self._build_ui()
    
    def _build_ui(self):
        """"""
        main_layout = MDBoxLayout(orientation='vertical', spacing="10dp")
        toolbar = MDTopAppBar(title="", left_action_items=[["arrow-left", lambda x: self._go_back()]])
        main_layout.add_widget(toolbar)
        content_layout = MDBoxLayout(orientation='vertical', spacing="20dp", padding="20dp", adaptive_height=True)
        self.video_info_card = VideoInfoCard()
        content_layout.add_widget(self.video_info_card)
        self.progress_card = ProgressCard()
        content_layout.add_widget(self.progress_card)
        button_layout = MDBoxLayout(orientation='horizontal', spacing="15dp", size_hint_y=None, height="50dp")
        self.cancel_btn = MDFlatButton(text=" ", size_hint_x=0.5)
        self.cancel_btn.bind(on_press=self._cancel_processing)
        button_layout.add_widget(self.cancel_btn)
        self.result_btn = MDRaisedButton(text=" ", size_hint_x=0.5, disabled=True, md_bg_color=self.theme_cls.primary_color)
        self.result_btn.bind(on_press=self._view_result)
        button_layout.add_widget(self.result_btn)
        content_layout.add_widget(button_layout)
        main_layout.add_widget(content_layout)
        self.add_widget(main_layout)
    
    def on_enter(self):
        """"""
        app = MDApp.get_running_app()
        if hasattr(app, 'selected_file') and app.selected_file:
            video_info = getattr(app, 'video_info', None)
            if video_info:
                self.video_info_card.update_video_info(video_info)
            self._start_processing(app.selected_file)
        else:
            toast("")
            self._go_back()
    
    def _start_processing(self, file_path):
        """"""
        if self.processing: return
        self.processing = True
        self.cancel_btn.text = " "
        self.result_btn.disabled = True
        self.progress_card.reset()
        app = MDApp.get_running_app()
        self.processing_thread = threading.Thread(
            target=self._process_video,
            args=(file_path, app.settings_data)
        )
        self.processing_thread.daemon = True
        self.processing_thread.start()
    
    def _process_video(self, file_path, settings):
        """"""
        app = MDApp.get_running_app()
        try:
            start_time = time.time()
            self.progress_card.update_progress(5, "...", "")
            
            video_processor = VideoProcessor()
            device = settings.get('device', 'auto') if settings.get('device', 'auto') != 'auto' else None
            transcriber = WhisperTranscriber(settings.get('whisper_model', 'base'), device)
            host = settings.get('ollama_host', 'localhost')
            port = settings.get('ollama_port', 11434)
            summarizer = VideoSummarizer(OllamaClient(base_url=f"http://{host}:{port}"), settings.get('ollama_model', 'qwen2:7b'))

            self.progress_card.update_progress(15, "...", f"{file_path}")
            audio_path = video_processor.extract_audio(file_path)
            temp_files = [audio_path]

            self.progress_card.update_progress(30, "...", f" {transcriber.model_name} ")
            transcript_result = transcriber.transcribe_audio(audio_path, settings.get('language', 'auto'))

            self.progress_card.update_progress(70, "...", f" {summarizer.model_name} ")
            summary_result = summarizer.generate_summary(
                transcript_result['text'],
                style=settings.get('summary_style', 'detailed'),
                language=transcript_result.get('language', 'en')
            )

            self.progress_card.update_progress(95, "...", "")
            end_time = time.time()

            app.result_data = {
                'transcript': transcript_result,
                'summary': summary_result,
                'video_info': app.video_info,
                'processing_time': f"{end_time - start_time:.2f} "
            }

            if settings.get('auto_cleanup', True):
                video_processor.cleanup_temp_files(temp_files)

            self._processing_completed()
            
        except Exception as e:
            self.progress_card.set_error(f": {str(e)}")
            self._processing_failed()
    
    def _processing_completed(self):
        """"""
        self.processing = False
        self.cancel_btn.text = " "
        self.result_btn.disabled = False
        toast("")
    
    def _processing_failed(self):
        """"""
        self.processing = False
        self.cancel_btn.text = " "
        self.result_btn.disabled = True
        toast("")
    
    def _cancel_processing(self, instance):
        """"""
        if self.processing:
            self.processing = False
            toast("")
            self._go_back()
        elif self.cancel_btn.text == " ":
            MDApp.get_running_app().navigate_to('upload')
        elif self.cancel_btn.text == " ":
            app = MDApp.get_running_app()
            if hasattr(app, 'selected_file'):
                self._start_processing(app.selected_file)
    
    def _view_result(self, instance):
        """"""
        MDApp.get_running_app().navigate_to('result')
    
    def _go_back(self):
        """"""
        if self.processing: 
            toast("")
            return
        MDApp.get_running_app().navigate_to('upload')
